Passed
Branchmaster (5eac25)
by Plamen
01:51
created

table.js ➔ ... ➔ this.ColumnHover   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 16
rs 8.6666
cc 6
nc 4
nop 2
1
var strAsc = String.fromCharCode(9650); //▲
2
var strDesc = String.fromCharCode(9660);//▼
3
var xmlhttp; var d;
4
5
var table = new function(){
6
    this.rq = null;
7
    this.tail = [];
8
9
    this.ReloadData = function(tableId){
10
        var request = {};
11
        this.BuildRequest(request,tableId);
12
        this.LoadData(tableId,request);
13
    };
14
15
    this.BuildRequest = function(request, crntTableId, skipPropertyArray){
16
        this.rq = request;
17
        this.checkSkip = function(skipProperty){
18
            var result = false;
19
            if(skipPropertyArray && Object.prototype
20
                .toString.call(skipPropertyArray) === '[object Array]'){
21
                if(skipPropertyArray.indexOf(skipProperty)>=0){
22
                    result = true;
23
                }
24
            }
25
            return result;
26
        };
27
        this.getSort = function(){
28
            var table = document.getElementById(crntTableId);
29
            var thTags = table.getElementsByTagName("thead")[0]
30
                        .getElementsByTagName("th");
31
            for(var i = 0; i < thTags.length; i++ ){
32
                if(thTags[i].getElementsByTagName("a")[0] && thTags[i]
33
                    .getElementsByTagName("a")[0].getElementsByTagName("span")
34
                    .length === 1
35
                ){
36
                    var order = thTags[i].getElementsByTagName("a")[0]
37
                                .getElementsByTagName("span")[0].innerHTML;
38
                    if(order.length === 1){
39
                        this.rq.colNo = i;
40
                        this.rq.colOrd = (order === window.strDesc) ?
41
                                            "desc" : "asc";
42
                    }
43
                }
44
            }
45
        };
46
        this.getFilter = function(){
47
            var r = this.getFilterFieldsByTbaleID(crntTableId);
48
            if(r.filter !== null){
49
                this.rq.filter = r.filter;
50
            }
51
            if(r.filterBy !== null){
52
                this.rq.filterBy = r.filterBy;
53
            }
54
        };
55
56
        /* Build request object */
57
        if(!this.checkSkip("sort")){            this.getSort();         }
58
        if(!this.checkSkip("filter")){          this.getFilter();       }
59
60
        this.rq.tableId = crntTableId;
61
        return this.rq;
62
    };
63
64
    this.RequestToUrl = function(rq){
65
        var url=location.pathname + ".json" + location.search;
66
        if(typeof rq === "object"){
67
            var getUrlVarName = {
68
                colNo: "col", colOrd: "ord", filter: "filter", 
69
                filterBy: "filter-by", pageNo: "pg", exportType: "export",
70
                tableId: "table-id"
71
            };
72
            var flagFirst = location.search.length < 1 ? true : false;
73
            for(var r in rq){
74
                if ( ! rq.hasOwnProperty(r)) {
75
                    continue; // Skip keys from the prototype.
76
                }
77
                var clue = flagFirst===true ? "?" : "&";
78
                url += clue + getUrlVarName[r] + "=" + rq[r];
79
                flagFirst = false;
80
            }
81
        }
82
        return url;
83
    };
84
85
    this.Filter = function(field){
86
        var request = {};
87
        var isSelect = field.tagName.toLowerCase() === "select";
88
        if(isSelect){
89
            var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
90
            if('' === f.value){
91
                return;
92
            }
93
            var crntTableId = f.getAttribute("data-table-id");
94
        } else {
95
            var crntTableId = field.getAttribute("data-table-id");
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable crntTableId already seems to be declared on line 93. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
96
        }
97
        var exRq = this.rq;
98
        this.BuildRequest(request,crntTableId);
99
        if(exRq===null){
100
            this.LoadData(crntTableId,request);
101
        } else if(  request.filter !== exRq.filter ||
102
                    request.filterBy !== exRq.filterBy
103
        ){
104
            this.LoadData(crntTableId,request);
105
        }
106
    };
107
108
    this.GoPage = function(lnk){
109
        var request = {};
110
        var table = this.getParent(lnk,"table");
111
        var crntTableId = table.getAttribute("id");
112
        this.BuildRequest(request,crntTableId);
113
        //check & serve pagination jump links
114
        var jumpDir=lnk.innerHTML.trim().substr(0,1);
115
        if(jumpDir==="+" || jumpDir==="-"){
116
            var current = table.querySelector("tfoot .paging .a").innerHTML;
117
            var jump = lnk.innerHTML.replace("K","000").replace("M","000000000");
118
            var jumpPage = (parseInt(current)+parseInt(jump));
119
            lnk.parentNode.setAttribute("data-page",jumpPage);
120
            lnk.style.transform="none";
121
        }
122
        request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
123
                         lnk.parentNode.getAttribute("data-page") :
124
                         lnk.innerHTML;
125
        this.LoadData(crntTableId,request);
126
        return false;
127
    };
128
129
    this.Export = function(lnk,eType){
130
        var request = {};
131
        var crntTableId = this.getParent(lnk,"table").getAttribute("id");
132
        this.BuildRequest(request,crntTableId);
133
        request.exportType = ["CSV","Excel"].indexOf(eType)>=0 ? eType : "csv";
134
        window.open(this.RequestToUrl(request));
135
        return false;
136
    };
137
138
    this.Sort = function(colNo,lnk){
139
        var request = {};
140
        var crntTableId = this.getParent(lnk,"table").getAttribute("id");
141
        this.BuildRequest(request,crntTableId);
142
        if(Math.round(colNo) === request.colNo){
143
            request.colOrd = request.colOrd === "asc" ? "desc" : "asc";
144
        } else {
145
            request.colNo=Math.round(colNo);
146
            request.colOrd = "asc";
147
        }
148
        this.LoadData(crntTableId,request);
149
        /* Clear and add new sort arrow */
150
        var headSpans = this.getParent(lnk,"thead").getElementsByTagName("span");
151
        for(var i=0; i < headSpans.length; i++){
152
            headSpans[i].innerHTML = "";
153
        }
154
        lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? window.strDesc : window.strAsc);
155
    };
156
157
    this.DrawSection = function(tableContainer, dt, tSection){
158
        var section = tSection === "tfoot" ? "tfoot" : "tbody";
159
        tSection =  document.getElementById(tableContainer).
160
                        getElementsByTagName(section)[0];
161
        this.clearSection(tSection);
162
        for(var i=0; i < dt.length; i++) {
163
            var row = dt[i];
164
            var tRow = document.createElement("tr");
165
166
            this.DrawRow(row, tRow);
167
168
            tSection.appendChild(tRow);
169
            if(section === "tfoot"){
170
                this.footerProcessPaginationLinks(tSection);
171
            }
172
            this.AppendRowCalback(tableContainer);
173
        }
174
    };
175
176
    this.DrawRow = function(row, tRow){
177
        for(var cell in row){
178
            if ( ! row.hasOwnProperty(cell)) {
179
                continue; // Skip keys from the prototype.
180
            }
181
            var tCell = document.createElement("td");
182
            if(typeof row[cell] === "string" || typeof row[cell] === "number"){
183
                tCell.innerHTML = row[cell];
184
            } else if(typeof row[cell] === "object"){
185
                this.DrawCellFromObject(row, cell, tCell);
186
            }
187
            tRow.appendChild(tCell);
188
        }
189
    };
190
191
    this.DrawCellFromObject = function(row, cell, tCell){
192
        for(var attr in row[cell]){
193
            if ( ! row[cell].hasOwnProperty(attr)) {
194
                continue; // Skip keys from the prototype.
195
            }
196
            if(typeof row[cell][attr] === "string"){
197
                tCell.innerHTML = row[cell][attr];
198
            } else if(typeof row[cell][attr] === "object"){
199
                for(var v in row[cell][attr]){
200
                    if ( ! row[cell][attr].hasOwnProperty(v)) {
201
                        continue; // Skip keys from the prototype.
202
                    }
203
                    tCell.setAttribute(v,row[cell][attr][v]);
204
                }
205
            }
206
        }
207
    };
208
209
    this.footerProcessPaginationLinks = function(tSection){
210
        var pLinks = tSection.querySelectorAll(".paging a");
211
        if(pLinks.length>0){
212
            for(var j=0; j < pLinks.length; j++){
213
                pLinks[j].setAttribute("href","javascript:void(0);");
214
                pLinks[j].setAttribute("onclick","return table.GoPage(this);");
215
            }
216
        }
217
    };
218
219
    this.clearSection = function(tSection){
220
        if(this.iePrior(9)){
221
            if(tSection.firstChild){
222
                while (tSection.firstChild) {
223
                    tSection.removeChild(tSection.firstChild);
224
                }
225
            }
226
        } else {
227
            tSection.innerHTML="";
228
        }
229
    };
230
231
    this.SetTheTableColumnsHoverEffect = function (tableContainer){
232
        if(this.iePrior(9)) {return;}
233
        var tContainer = document.getElementById(tableContainer);
234
        var tHcells = tContainer.rows[0].cells;
235
        for(var i=0; i < tHcells.length; i++){
236
            if(tHcells[i].firstChild.tagName === "A"){
237
                tHcells[i].firstChild.setAttribute("onmouseover","table.ColumnHover('"+tableContainer+"',"+i+");");
238
                tHcells[i].firstChild.setAttribute("onmouseout","table.ColumnHover('"+tableContainer+"');");
239
            }
240
        }
241
        var pLinks = tContainer.querySelectorAll("tfoot .paging a");
242
        if(pLinks.length>0){
243
            for(var j=0; j < pLinks.length; j++){
244
                pLinks[j].setAttribute("href","javascript:void(0);");
245
                pLinks[j].setAttribute("onclick","return table.GoPage(this);");
246
            }
247
        }
248
    };
249
250
    this.ColumnHover = function(tableContainer,index){
251
        if(this.iePrior(9)) {return;}
252
        var tRow = document.getElementById(tableContainer).rows;
253
        index = Math.round(index);
254
        for(var i=0; i < (tRow.length-1); i++){
255
            if(index >= 0){
256
                tRow[i].cells[index].setAttribute("lang","col-hover");
257
            } else {
258
                for(var j=0; j < tRow[i].cells.length; j++){
259
                    if(tRow[i].cells[j].lang){
260
                        tRow[i].cells[j].removeAttribute("lang");
261
                    }
262
                }
263
            }
264
        }
265
    };
266
267
    this.getFilterFieldsByTbaleID = function(tableID){
268
        var fields = {filterBy:null, filter:null};
269
        var filterDiv = this.getFilterDivByTableIDOrNull(tableID);
270
        if(filterDiv!==null) {
271
            var selectObj = filterDiv.getElementsByTagName("select")[0];
272
            var textObj = filterDiv.getElementsByTagName("input")[0];
273
            fields.filterBy = (selectObj===null || selectObj.options[selectObj.selectedIndex].value==="all") ? null : selectObj.options[selectObj.selectedIndex].value;
274
            fields.filter = (textObj===null || textObj.value.length === 0) ? null : encodeURIComponent(textObj.value.trim());
275
        }
276
        return fields;
277
    };
278
279
    this.getFilterDivByTableIDOrNull = function(tableID){
280
        var res = null;
281
        if(document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0){
282
            for (var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++) {
283
                if(document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class")==="filter"){
284
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
285
                }
286
            }
287
288
        }
289
        return res;
290
    };
291
292
    this.LoadData = function(tableContainer,rq){
293
        this.setVisability(tableContainer, false);
294
        if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();/* global:XMLHttpRequest - code for IE7+, Firefox, Chrome, Opera, Safari */
295
        } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");/* global: ActiveXObject - code for IE6, IE5 */}
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
296
        for (var i = 0; i < this.tail.length; i++) {
297
            var ex_xmlhttp = this.tail.shift();
298
            ex_xmlhttp.abort();
299
        }
300
        xmlhttp.onreadystatechange = function() {
301
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
302
                d = JSON.parse(xmlhttp.responseText);
303
                table.DrawSection(tableContainer,d.body);
304
                table.DrawSection(tableContainer,d.footer,"tfoot");
305
                table.LoadEndCalback(tableContainer);
306
                table.setVisability(tableContainer, true);
307
                if(typeof rq === "object"){
308
                    table.ColumnHover(tableContainer,rq.colNo);
309
                }
310
            }
311
        };
312
        xmlhttp.open("GET", this.RequestToUrl(rq), true);
313
        xmlhttp.send();
314
        this.tail.push(xmlhttp); //put in tail to may later abort any previous
315
    };
316
317
    this.setVisability = function(tableContainer,rq){
318
        var tbl = document.getElementById(tableContainer);
319
        if(rq===true){
320
            tbl.style.filter = "none";
321
            tbl.style.opacity = "1";
322
            tbl.style.cursor = "auto";
323
        } else if(rq===false){
324
            tbl.style.filter = "blur(1px)";
325
            tbl.style.opacity = "0.8";
326
            tbl.style.cursor = "wait";
327
        } else { console.log("table error in the rq value"); /*Shows error*/}
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
328
    };
329
330
    this.getParent = function (obj,objType){
331
        while( obj && obj.tagName !== objType.toUpperCase() ){
332
            obj = obj.parentNode;
333
        } return obj;
334
    };
335
336
    this.init = function(tableId){
337
        this.SetTheTableColumnsHoverEffect(tableId);
338
    };
339
340
    this.iePrior = function(v) {var rv=false; if(navigator.appName/** global: navigator */==='Microsoft Internet Explorer') {var ua=navigator.userAgent; var re=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if(re.exec(ua)!==null){rv=parseFloat(RegExp.$1);} rv=rv<v?true:false; } return rv;};
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
341
    this.loadJS = function(src){ var s = document.createElement('script'); s.src = src; document.getElementsByTagName('head')[0].appendChild(s);};
342
    this.loadCSS = function(src){ var s = document.createElement('link'); s.href = src; s.rel="stylesheet"; document.getElementsByTagName('head')[0].appendChild(s);};
343
344
    this.LoadEndCalback = function(tableId){/* Allows override if(tableId){}*/};
0 ignored issues
show
Unused Code introduced by
The parameter tableId is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
345
    this.AppendRowCalback = function(tableId){/* Allows override if(tableId){}*/};
0 ignored issues
show
Unused Code introduced by
The parameter tableId is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
346
};
347
348
/** Moves custom created filter to the Table's filter
349
 * @param {string} filterId
350
 * @param {string} tableId
351
 * @param {boolean} delay - needed in case the table is istill not executed */
352
function moveSelectorToTheTableFilter(filterId, tableId, delay){
353
    if(delay===true){
354
        setTimeout(function(){
355
            var filterDiv = document.getElementById(tableId)
356
                            .getElementsByTagName("div")[0];
357
            filterDiv.appendChild(document.getElementById(filterId));
358
        },500);
359
    } else {
360
        var filterDiv = document.getElementById(tableId)
361
                        .getElementsByTagName("div")[0];
362
        filterDiv.appendChild(document.getElementById(filterId));
363
    }
364
}
365
function changeListCustomFilter(selectObj){
366
    var fId = selectObj.options[selectObj.selectedIndex].value;
367
    var varName = selectObj.getAttribute("name");
368
    var varPos = document.URL.indexOf(varName);
369
    if(varPos>0){
370
        var url = fId!=="{!--Empty--!}" ? document.URL.substring(0,varPos) : document.URL.substring(0,(varPos-1));
371
    } else {
372
        var separator = document.URL.indexOf("?")>0 ? "&" : "?";
373
        url = document.URL + (fId!=="{!--Empty--!}" ? separator : "");
374
    }
375
    var newUrl = url + (fId!=="{!--Empty--!}" ? (varName + "=" + fId) : "");
376
    location.assign(newUrl);
377
}
378
379
380
function tablesLoadData(){
381
    var tables = document.getElementsByTagName("table");
382
    var envPrior9 = table.iePrior(9);
383
    for (var i = 0; i < tables.length; i++) {
384
        var isProcessable = envPrior9 ?
385
                            typeof tables[i]["data-table"]!== 'undefined' :
386
                            tables[i].hasAttribute("data-table");
387
        if(isProcessable && tables[i].getAttribute("data-table") === "js"){
388
            table.LoadData(tables[i].id);
389
            table.SetTheTableColumnsHoverEffect(tables[i].id);
390
        }
391
    }
392
    if(table.iePrior(10)){
393
        table.loadJS("/add/helpers/table/add/json2.js");
394
    }
395
396
    /*if(table.iePrior(8)){ //can be used to add apropriate tables links modifications
397
        // loadCSS("/add/helpers/table/add/ie7-and-down.css");
398
    }*/
399
}
400
401
/*if(window.addEventListener){window.addEventListener('load',tablesLoadData,false);} else if(window.attachEvent){window.attachEvent('onload',tablesLoadData);}*/